import * as map from "./map.js"
//获取游戏容器dom对象
const firstMap = deepClone(map.allMap);
window.firstMap = firstMap
const gameMap = document.querySelector('#game');
//渲染地图
function renderMap() {
    gameMap.innerHTML = "";
    gameMap.style.width = map.oneItemW * map.mapWidth + "px";
    gameMap.style.height = map.oneItemH * map.mapHeight + "px";
    map.allMap.forEach((row, rowIndex) => {
        row.forEach((col, colIndex) => {
            render(col, rowIndex, colIndex)
        })
    })
}
//每一次渲染
function render(col, rowIndex, colIndex) {
    if (col === map.player) {
        //根据对应的对象设置不同的样式和位置
        addItem("player", colIndex, rowIndex)
    } else if (col === map.wall) {
        addItem("wall", colIndex, rowIndex)
    } else if (col === map.box) {
        addItem("box", colIndex, rowIndex)
    } else {
        if (isCorrectPosition(rowIndex, colIndex)) {
            addItem("correctBox", colIndex, rowIndex)
        } else {
            return;
        }
    }
    const renderItem = document.querySelectorAll("#game div");
    for (const item of renderItem) {
        item.classList.add("item");
    }
}
//添加dom元素
function addItem(className, colIndex, rowIndex) {
    const item = document.createElement("div");
    item.className = className;
    changePosition(item, colIndex, rowIndex)
    gameMap.appendChild(item);
}
//改变dom元素位置
function changePosition(dom, colIndex, rowIndex) {
    dom.style.left = colIndex * map.oneItemH + "px";
    dom.style.top = rowIndex * map.oneItemW + "px";
}
//判断是否是正确位置
export function isCorrectPosition(rowIndex, colIndex) {
    return map.correctPosition.find(it => rowIndex === it.row && colIndex === it.col) != undefined
}
function deepClone(arr,target = []) {
    const newArr = target;
    for (const prop in arr) {
        if (Object.prototype.toString.call(arr[prop]) === "[object Array]") {
             newArr[prop] = deepClone(arr[prop]);
        } else {
            newArr[prop] = arr[prop];
        }
    }
    return newArr;
}
//重绘
export function reset() {
    deepClone(firstMap,map.allMap);
}
//导出模块
export default renderMap;